// pages/recharge/recharge.js
let app =getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userBean: null,
    coinList:[],
    current:0 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    new app.WeToast();
    this.getCoinList();
    this.setData({
      userBean: app.globalData.userBean()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  getCoinList(){
    app.httpUtils.postLoading(app.Api.GETGOODS,{}).then(res => {
        if(res.code == '00'){
          this.setData({
            coinList:res.data
          })
        }
    })
  } ,

  selectPrice(e){
    let index = e.currentTarget.dataset.index
    this.setData({
      current :index
    })
  },

  getCode(){
   let gid  =  this.data.coinList[this.data.current].id
   wx.showLoading({ title: '请稍等', })
   app.httpUtils.login().then(res => {
      wx.hideLoading();
      this.recharge(gid, res.code)
    })
  },

  recharge(gid,code){
    let that = this;
    app.httpUtils.postLoading(app.Api.RECHARGEBYMICROMSG,{
      uid: app.globalData.userBean().id,
      gid: gid,
      js_code: code 
    }).then(res => {
      if(res.code=='00'){
        var data = res.data.msg;
        console.log(data)
         wx.requestPayment({
           'timeStamp': data.timeStamp+"",
           'nonceStr': data.nonceStr,
           'package': data.package,
           'signType': data.signType,
           'paySign': data.paySign,
           'success': function (res) {
             that.wetoast.toast({
               title: "充值成功",
               duration: 1000
             })
           },
           'fail': function (res) {
             that.wetoast.toast({
               title: res.errMsg,
               duration: 1000
             })
           }
         })
      }else {
        that.wetoast.toast({
          title: res.msg,
          duration: 1000
        })
      }
    })
  }

})